$NG.AllReady(function (page, { useDataIndexChange, useValuesChange, useClick, useUpdateRows }) {
    if (page.oType == "add") {
        getGzZc()
        cntMFilter()
    }
    const mstform = $NG.getCmpApi("p_form_sub_ys_m");
    const grid = $NG.getCmpApi("p_form_sub_ys_d");
    const grid1 = $NG.getCmpApi("p_form_sub_ys_d1");
    const grid2 = $NG.getCmpApi("p_form_sub_ys_d2");

    function setTitle() {
        const u_cnt_name = (String(mstform.getItem("u_cnt_name").getText()) || 0)
       // const gzdy = (String(mstform.getItem("phid_cycle").getText()) || 0)
        $NG.updateState((updater) => {
            updater.data.p_form_sub_ys_m.setProps({
                bill_name: `${u_cnt_name}分包决算`
            })
        })
    }
    useValuesChange(({ args }) => {
        console.log(`监听合同变化`, args);
        const _data = args[0]
        const htvalue = _data.u_cnt_name.value;
        cntMFilter()
        getCntMInfoByPhid()
        FBJS(htvalue)
        setTitle()
    }, "p_form_sub_ys_m.u_cnt_name")

    useValuesChange(({ args }) => {
        cntMFilter()
        setTitle()
    }, "p_form_sub_ys_m.phid_pc")

    useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)
        record.u_wjs_qty = (parseFloat(record.u_bqjs_qty) - parseFloat(record.u_js_qty));
        record.u_change_qty = (parseFloat(record.u_bqjs_qty) - parseFloat(record.u_cnt_qty));
        record.u_js_amt = (parseFloat(record.u_bqjs_qty) * parseFloat(record.u_cnt_prc_vat));
        record.u_wjs_amt_vat = parseFloat(record.u_js_amt) - (parseFloat(record.u_cnt_qty) * parseFloat(record.u_cnt_prc_vat));
        grid.updateRow(args[0]);

    }, "u_bqjs_qty");

    useUpdateRows(({ args }) => {
        sumAmt()
        // grid.updateRow(rows);
    }, "p_form_sub_ys_d")

    useUpdateRows(({ args }) => {
        sumAmt()
        // grid.updateRow(rows);
    }, "p_form_sub_ys_d1")

    useUpdateRows(({ args }) => {
        sumAmt()

        // grid.updateRow(rows);
    }, "p_form_sub_ys_d2")

    function sumAmt(){
        var sumAmt = 0;
        const rows = grid.getData();
        const rows1 = grid1.getData();
        const rows2 = grid2.getData();
        rows.forEach((items) => {
            if (items.u_js_amt) {
                sumAmt += parseFloat(items.u_js_amt);  //明细
            }
        });
        let jfAmt = rows1.reduce((value,item)=>{
            if (item.u_jf_lx == '2') {
                value -= (Number(item.u_amt_vat) || 0)
            } else {
                value += (Number(item.u_amt_vat) || 0)
            }
            return value
        },0)
        let wlAmt = rows2.reduce((value,row)=>{
            row.u_ch_qty = row.u_sy_qty - ((Number(row.u_bzyl) || 0) * (1 + (Number(row.u_bzshl) || 0)))
            row.u_out_je = (Number(row.u_ch_qty) || 0) <=0? 0:row.u_ch_qty * row.u_prc
            row.u_yk_out_je = (Number((Number(row.u_out_je) || 0) - (Number(row.u_ykc_out_je) || 0)) || 0)
            value += (Number(row.u_yk_out_je) || 0)
            return value
        },0)
        //汇总赋值到表头字段
        $NG.updateState((updater) => {
            updater.data.p_form_sub_ys_m.setProps({
                u_jsamt_vat: sumAmt,  //表头：
                u_jsamt_total:sumAmt + jfAmt - wlAmt,
                u_rest_amt:(sumAmt + jfAmt - wlAmt) - (Number(mstform.getItem("u_ljjsze").getValue()) || 0)
            });
        });
        grid.refreshView()
        grid1.refreshView()
        grid2.refreshView()
    }

    function FBJS(htvalue) {
        //FBJS_info
        grid.clearRows();
        grid1.clearRows();
        grid2.clearRows();
        $NG.execServer('FBJS_info', { ht: htvalue }, function (res) {
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            var gridArr = []; // 定义表体数组
            var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
            console.log(`带出调试`,data);
            for (var i = 0; i < gridCount; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {};

                gridObj.u_sbqd_no = data[i].extendObjects.u_sbqd_no;
                gridObj.u_sbqd_name = data[i].extendObjects.u_sbqd_name;
                gridObj.u_sbqd_name_EXName = data[i].extendObjects.u_equipment_list_name
                gridObj.u_cnt_qd_no = data[i].extendObjects.u_cnt_qd_no;
                gridObj.u_cnt_qd_name = data[i].extendObjects.u_cnt_qd_name;
                gridObj.u_cnt_qd_name_EXName = data[i].extendObjects.itemname;
                gridObj.u_cnt_qty = data[i].extendObjects.u_cnt_qty;
                gridObj.u_cnt_prc = data[i].extendObjects.u_cnt_prc;
                gridObj.u_cnt_prc_vat = data[i].extendObjects.u_cnt_prc_vat;
                gridObj.u_js_qty = data[i].extendObjects.u_yjs_qty;
                gridObj.u_sl = data[i].extendObjects.u_tax;
                gridObj.u_ljjs_amt = data[i].extendObjects.u_ljjs_amt_vat;
                gridObj.u_bqjs_qty = data[i].extendObjects.u_cnt_qty-data[i].extendObjects.u_cnt_qty;
                gridObj.u_change_qty = data[i].extendObjects.u_tax;
                gridObj.u_js_amt = data[i].extendObjects.u_cnt_qty * data[i].extendObjects.u_cnt_prc_vat;
                gridObj.u_wjs_qty = data[i].extendObjects.u_cnt_qty - data[i].extendObjects.u_yjs_qty;
                gridObj.u_wjs_amt_vat = (data[i].extendObjects.u_cnt_qty * data[i].extendObjects.u_cnt_prc_vat) - data[i].extendObjects.u_ljjs_amt_vat;


                gridArr.push(gridObj);
            }
            console.log(`带出整理调试`,gridObj);
            // 清空表格内容（放在循环外部）

            grid.addRows(gridArr);
            grid.refreshView();
        });


        $NG.execServer("FBJS_info_JF", { ht: htvalue }, function (res) {
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            var gridArr = []; // 定义表体数组
            var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行

            for (var i = 0; i < gridCount; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {};

                gridObj.u_jf_lx = data[i].extendObjects.u_jf_lx;
                gridObj.u_charge_name = data[i].extendObjects.u_charge_name
                gridObj.u_amt_vat = data[i].extendObjects.u_amt_vat;
              
                gridArr.push(gridObj);
            }
            // 清空表格内容（放在循环外部）

            grid1.addRows(gridArr);
            grid1.refreshView();
        });




        $NG.execServer("FBJS_info_jg", { ht: htvalue }, function (res) {
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            var gridArr = []; // 定义表体数组
            var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行

            for (var i = 0; i < gridCount; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {};

                gridObj.u_item_name = data[i].extendObjects.u_item_name;
                gridObj.u_item_name_EXName = data[i].extendObjects.itemname
                gridObj.u_spec = data[i].extendObjects.u_spec;
                gridObj.u_unit = data[i].extendObjects.u_unit;
                gridObj.u_unit_EXName = data[i].extendObjects.msname;
                gridObj.u_prc = data[i].extendObjects.u_prc;
                gridObj.u_bzshl = data[i].extendObjects.u_bzshl;
                gridObj.u_htshl = data[i].extendObjects.u_htshl;
                gridObj.u_ly_qty = data[i].extendObjects.u_ly_qty;
                gridObj.u_kc_qty = data[i].extendObjects.u_kc_qty;
                gridObj.u_sy_qty = data[i].extendObjects.u_sy_qty;
                gridObj.u_bzyl = data[i].extendObjects.u_bzyl;
                gridObj.u_ch_qty = data[i].extendObjects.u_ch_qty;
                gridObj.u_out_je = data[i].extendObjects.u_out_je;
                gridObj.u_ykc_out_je = data[i].extendObjects.u_ykc_out_je;
                gridObj.u_yk_out_je = data[i].extendObjects.u_yk_out_je;
                gridArr.push(gridObj);
            }
            // 清空表格内容（放在循环外部）

            grid2.addRows(gridArr);
            grid2.refreshView();
        });

    }

    //获取合同信息
    function getCntMInfoByPhid() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        console.log(`开始获取合同`);
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("u_cnt_name").getValue() },
            function (res) {
                if (res.count == 0) return
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_ys_m.setProps({
                        u_cnt_no: datas.pcm_no, //合同编码
                        u_fbht_amt: datas.cnt_sum_vat_fc, //合同价税合计
                        //合同类型
                        pct_id: { value: datas.pct_id, label: datas.pct_name },
                        //甲方单位
                        u_dept_a: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        //乙方单位
                        u_yf_dept: {
                            value: datas.supply_id,
                            label: datas.supply_name,
                        },
                    });
                });
            }
        );

        $NG.execServer(
            "FBJS_info_m",
            { ht: mstform.getItem("u_cnt_name").getValue() },
            function (res) {
                if (res.count == 0) return
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_ys_m.setProps({
                        u_ljjs_amt: datas.u_yjs_amt, 
                        u_ljjsze: datas.u_yjs_jfd_amt, 
                        u_ljfk_amt: datas.u_ljfk_amt, 

                    });
                });
            }
        );
    }

    //获取工作周期
    function getGzZc() {
        let _count = {}
        $NG.execServer("getInDate", {}, function (res) {
            console.log(`获取工作周期`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_ys_m.setProps({
                    phid_cycle: {
                        label: _data.bill_name,
                        value: _data.phid
                    }
                })
            })
        })
    }


    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log("过滤参数检查", updater);
            updater.fieldSetForm.p_form_sub_ys_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_sub_ys_m").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_sub_ys_m").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        'pcm3_cnt_m.phid_pc': $NG.getCmpApi("p_form_sub_ys_m").getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }
    // 获取分包结算已超耗金额
    window._catch_cnt_cc_amt = []
    getFbhtjsWlTotalamt()
    async function  getFbhtjsWlTotalamt(){
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if(!cnt){ return }
        await $NG.execServer("getFbhtjsWlTotalamt", { cnt },async function (res) {
            console.log(`查询物料超耗金额:${res.count}`,res);
            if(res.count == 0)return 
            window._catch_cnt_cc_amt = JSON.parse(res.data).reduce((value,items)=>{
                const item = items.extendObjects
                value.push(item)
                return value
            },[])
        })
    }

});


